package com.lin.sqltool.controller;

import com.lin.sqltool.dialog.ConfigDialog;
import com.lin.sqltool.dialog.ConnectionDialog;
import com.lin.sqltool.listener.SimpleConnectionListener;
import com.lin.sqltool.model.ConnectionInfoModel;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.AnchorPane;

import java.io.IOException;

public class MainController {


    @FXML
    private TabPane mainTabPane;


    @FXML
    public Label leftLabel;

    @FXML
    public Label rightLabel;


    @FXML
    public void initialize() {
        // 初始化时自动打开连接对话框
        Platform.runLater(this::handleNewConnection);
    }

    /**
     * 新增连接
     */
    @FXML
    public void handleNewConnection() {
        new ConnectionDialog(info -> {
            try {
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ConnectTabView.fxml"));
                Tab tabContent = loader.load();
                ConnectionTabController controller = loader.getController();
                controller.setConnectionInfo(info); //传递连接信息
                tabContent.setText(info.getName());
                mainTabPane.getTabs().add(tabContent);
                mainTabPane.getSelectionModel().select(tabContent); //设置选中状态

                if (mainTabPane.getTabs().size() == 1) {
                    Tab addTab = new Tab(" + ");
                    addTab.setClosable(false);
//                    mainTabPane.getTabs().add(addTab);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 关闭当前连接
     */
    public void handleCloseCurrentConnection(){
        for (Tab tab : mainTabPane.getTabs()) {
            if (tab.isSelected()) {
                mainTabPane.getTabs().remove(tab);
                break;
            }
        }
    }

    /**
     * 打开配置文件
     * @param actionEvent
     */
    @FXML
    public void handleOpenConfig(ActionEvent actionEvent) {
        new ConfigDialog();
    }


}
